<template>
  <page-view class="page-view" :title="false">
    <div slot="headerContent">
      <a-breadcrumb class="s-breadcrumb">
        <a-breadcrumb-item>资产管理</a-breadcrumb-item>
        <a-breadcrumb-item>出入库管理</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-card class="s-card">
      <div class="filter">
        <a-form>
          <a-row>

            <a-col :lg="16" :md="20" :sm="24">
              <a-col :lg="12" :md="12" :sm="24">
                <a-form-item label="库存类型" v-bind="formItemLayout">
                  <a-select v-model="tempQueryParam.stockType" placeholder="请选择" :options="typeList" allow-clear />
                </a-form-item>
              </a-col>

              <a-col :lg="12" :md="12" :sm="24">
                <a-form-item label="处理状态" v-bind="formItemLayout">
                  <a-select
                    v-model="tempQueryParam.status"
                    allow-clear
                    placeholder="请选择"
                    :options="(/库$/.test(tempQueryParam.stockType) ? [...statusList].filter(i => statusFilter[tempQueryParam.stockType].includes(i.label)) : statusList)"
                  />
                </a-form-item>
              </a-col>

              <a-col :lg="12" :md="12" :sm="24">
                <a-form-item label="申请人" v-bind="formItemLayout">
                  <a-input v-model="tempQueryParam.userName" placeholder="请输入" allow-clear />
                </a-form-item>
              </a-col>

              <a-col :lg="12" :md="12" :sm="24">
                <a-form-item label="审批人" v-bind="formItemLayout">
                  <a-input v-model="tempQueryParam.approverName" placeholder="请输入" allow-clear />
                </a-form-item>
              </a-col>
            </a-col>

            <a-col :lg="8" :md="4" :sm="24">
              <div class="btn-container">
                <a-button type="primary" @click="handleSearch">查询</a-button>
                <a-button @click="reset">重置</a-button>
                <a-button @click="handleExport">导出报表</a-button>
              </div>
            </a-col>

          </a-row>
        </a-form>
      </div>

      <s-table
        ref="table"
        class="s-table"
        bordered
        row-key="id"
        :row-selection="{ onChange }"
        :locale="{ emptyText: '暂无数据' }"
        :show-pagination="false"
        :columns="columns"
        :data="loadData"
        :alert="false"
      >
        <template slot="goods" slot-scope="item">
          <div style="text-align: center;" :title="item.goods">{{ item.goods }}</div>
        </template>
        <template slot="action" slot-scope="item">
          <div class="action-container end" style="width: 96px">
            <span
              v-if="/(出|入)库/.test(item.stockType) && /4/.test(item.status)"
              class="primary-link"
              style="padding-right: 0;"
              @click="handleItem(item)"
            >{{ item.stockType === '出库' ? '出库' : '入库' }}</span>
            <span class="success-link" @click="checkPDF(item)">查看报表</span>
          </div>
        </template>
      </s-table>
      <!-- 分页器 -->
      <div class="pagination-container">
        <a-pagination
          :page-size="queryParam.pageSize"
          :show-total="total => `共 ${total} 条记录 第 ${queryParam.pageNum} / ${Math.ceil(total / queryParam.pageSize)} 页`"
          :current="queryParam.pageNum"
          :total="count"
          hide-on-single-page
          show-quick-jumper
          @change="handlePage"
        />
      </div>

    </a-card>

    <PDFModal
      :url="url"
      :visible="showPDF"
      :title="modalTitle"
      :extra-text="modalText"
      @cancel="showPDF = false"
    />

  </page-view>
</template>

<script>
import { PageView, STable, PDFModal } from '@/components'
import { mapActions } from 'vuex'

const statusMaps = {
  4: '待处理',
  6: '待领取',
  8: '已完成',
  9: '已失效',
  11: '已撤销'
}

export default {
  name: 'Warehouse',
  components: { PageView, STable, PDFModal },
  inject: ['formItemLayout'],

  data () {
    return {
      typeList: [
        { value: '出库', label: '出库' },
        { value: '入库', label: '入库' },
        { value: '其他', label: '其他' }
      ],
      statusList: [
        { value: '4', label: '待处理' },
        { value: '6', label: '待领取' },
        { value: '8', label: '已完成' },
        { value: '9', label: '已失效' },
        { value: '11', label: '已撤销' }
      ],
      statusMaps,
      statusFilter: {
        出库: ['待处理', '已完成', '已撤销'],
        入库: ['待处理', '待领取', '已完成', '已失效', '已撤销']
      },

      tempQueryParam: {
        stockType: undefined,
        status: undefined,
        userName: undefined,
        approverName: undefined
      },
      count: 0,

      columns: [
        { title: '库存类型', width: '8%', align: 'center', dataIndex: 'stockType' },
        { title: '关联单号', width: '10%', align: 'center', dataIndex: 'sn' },
        { title: '关联类型', width: '8%', align: 'center', dataIndex: 'applyType' },
        { title: '申请人', width: '9%', align: 'center', dataIndex: 'userName' },
        { title: '经办人(仓管员)', width: '10%', align: 'center', dataIndex: 'handlerName' },
        { title: '物品名称', align: 'center', scopedSlots: { customRender: 'goods' }},
        { title: '申请日期', width: '10%', align: 'center', dataIndex: 'createdDate' },
        { title: '处理状态', width: '8%', align: 'center', dataIndex: 'statusName' },
        { title: '操作', width: '96px', align: 'center', scopedSlots: { customRender: 'action' }}
      ],

      rowItems: [],
      rowIds: [],

      showPDF: false,
      modalTitle: '',
      modalText: '',
      url: '',
      fileName: ''
    }
  },

  computed: {
    queryParam () { return this.$store.state.property.warehouseQueryParam }
  },

  watch: {
    queryParam: {
      handler (obj) {
        const target = this.tempQueryParam
        for (const key in target) {
          target[key] = obj[key]
        }
        this.$forceUpdate()
      },
      immediate: true,
      deep: true
    }
  },

  methods: {
    ...mapActions('property', ['setQueryParam']),

    loadData () {
      const { queryParam, statusMaps, $axios, $get, $moment } = this
      const params = {}
      for (const key in queryParam) {
        const item = queryParam[key]
        if (item) params[key] = item
      }
      this.count = 0
      const res = { data: [] }

      return $axios.post('api/assetsApply/queryOutbound', params).then(res => {
        this.count = $get(res, 'data.data.count', 0)
        res.data = $get(res, 'data.data.dataList', []).map(item => {
          const createdDate = item.createdTime ? $moment(item.createdTime).format('YYYY.MM.DD') : '-'
          if (!item.sn) item.sn = '-'
          if (!item.goods) item.goods = '-'
          if (!item.handlerName) item.handlerName = '-'
          return Object.assign(item, { createdDate, statusName: $get(statusMaps, item.status, '-') })
        })
        return res
      }).catch(e => res)
    },

    // 出入库
    handleItem (item) {
      this.$router.push(`warehouse/handle/${item.id}/${item.applyType}`)
    },

    checkPDF ({ id, applyType, sn, status }) {
      if (id === -1) return false

      this.modalTitle = applyType
      this.modalText = `${applyType.replace('单', '')}状态：${statusMaps[status]}`
      this.url = ''
      this.fileName = ''

      this.$toggleSending(1)
      this.$axios({
        url: `api/assetsApply/down/${id}`,
        responseType: 'arraybuffer',
        method: 'get',
        contentType: 'application/pdf;charset=utf-8'
      }).then(res => {
        if (!res.data.code) {
          const blob = new Blob([res.data], { type: 'application/pdf;charset=utf-8' })
          this.url = window.URL.createObjectURL(blob)
          this.fileName = `${applyType}_${sn}_${Date.now()}`
          this.showPDF = true
          this.$toggleSending()
        }
      }).catch(e => [])
    },

    onChange (ids, items) {
      this.rowIds = ids
      this.rowItems = items
    },

    refresh () {
      this.rowIds.splice(0)
      this.rowItems.splice(0)
      this.$refs.table.refresh()
    },

    handleSearch () {
      const { queryParam, setQueryParam, tempQueryParam, handlePage } = this
      const value = { ...tempQueryParam }
      setQueryParam({ target: queryParam, value })
      handlePage()
    },

    handlePage (pageNum = 1) {
      this.setQueryParam({ target: this.queryParam, value: { pageNum }})
      this.refresh()
    },

    reset () {
      Object.assign(this.tempQueryParam, { stockType: undefined, status: undefined, userName: undefined, approverName: undefined })
    },

    async handleExport () {
      const { rowIds, rowItems, $message, queryParam } = this
      if (!rowItems.length) {
        $message.destroy()
        $message.error('请选择要导出的报表')
        return false
      }
      this.$toggleSending(1)
      const param = Object.assign({}, queryParam, {
        ids: rowItems.map(i => i.id).join(','),
        pageNum: undefined,
        pageSize: undefined
      })
      const fileName = `出入库报表_${Date.now()}`
      const bool = await this.$exportFile({ url: 'api/assetsApply/exportOutbound', param, fileName })
      if (bool) {
        rowIds.splice(0)
        rowItems.splice(0)
      }
      this.$toggleSending()
    }
  }
}
</script>

<style lang="less" scoped>
  .filter {
    margin-bottom: 20px;
  }
</style>
